package com.leyou.item.service;

import com.leyou.common.exception.LyException;
import com.leyou.common.exception.enums.ExceptionEnum;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LT
 * @version 1.0.0
 * @ClassName CategoryService.java
 * @Description TODO 分类业务类
 * @createTime 2020年04月30日 21:42:00
 */
@Service
@Transactional
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据父id查询类别
     *
     * @param pid
     * @return
     */
    public List<CategoryDTO> findCategoryByPid(Long pid) {
        // 查询
        Category category = new Category();
        category.setParentId(pid);
        // 根据条件做查询
        List<Category> categoryList = categoryMapper.select(category);

        // 判空
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        // 把对象转换成DTO
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }

    /**
     * 根据分类id集合查询分类列表信息
     *
     * @param ids
     * @return
     */
    public List<CategoryDTO> findCategoryListByIds(List<Long> ids) {
        // 查询
        List<Category> categories = categoryMapper.selectByIdList(ids);
        // 判断
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 把对象转换成DTO
        return BeanHelper.copyWithCollection(categories, CategoryDTO.class);
    }

    /**
     * 根据分类的id查询父分类为key子分类列表为key的map
     *
     * @param pid
     * @return
     */
    public Map<String, List<CategoryDTO>> findCategoryMapById(Long pid) {
        // 查询
        Category record = new Category();
        record.setParentId(pid);
        List<Category> categoryList = categoryMapper.select(record);

        // 判断
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 转换
        List<CategoryDTO> categoryDTOList = BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
        Map<String, List<CategoryDTO>> map = new HashMap<>();

        // 迭代出每个Category
        for (CategoryDTO categoryDTO : categoryDTOList) {
            Category category = new Category();
            category.setParentId(categoryDTO.getId());
            List<Category> categoryValueList = categoryMapper.select(category);
            map.put(categoryDTO.getName(), BeanHelper.copyWithCollection(categoryValueList, CategoryDTO.class));
        }

        // 把对象转成dto
        return map;
    }
}
